package com.bx.implatform.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.bx.imcommon.util.JwtUtil;
import com.bx.implatform.config.JwtProperties;
import com.bx.implatform.enums.ResultCode;
import com.bx.implatform.exception.GlobalException;
import com.bx.implatform.session.UserSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@AllArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 从 http 请求头中取出 token
        String token = request.getHeader("accessToken");
        log.info("token1 {}", token);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("Authorization");
            if (StringUtils.isBlank(token)) {
                token = request.getHeader("nid");
            }
            log.info("token2 {}", token);
        } else {
            // 验证 token
            if (!JwtUtil.checkSign(token, jwtProperties.getAccessTokenSecret())) {
                log.error("token已失效，url:{}", request.getRequestURI());
                throw new GlobalException(ResultCode.INVALID_TOKEN);
            }
            // 存放session
            String strJson = JwtUtil.getInfo(token);
            UserSession userSession = JSON.parseObject(strJson, UserSession.class);
            request.setAttribute("session", userSession);
            return true;
        }
        if (StrUtil.isEmpty(token)) {
            log.error("未登陆，url:{}", request.getRequestURI());
            throw new GlobalException(ResultCode.NO_LOGIN);
        }

        UserSession userSession = new UserSession();
        userSession.setUserId(Long.valueOf(token));
        userSession.setTerminal(1);
        request.setAttribute("session", userSession);
        return true;
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
    }
}
